package com.learn.cloud.validator.constraints;

import cn.hutool.core.util.StrUtil;
import com.learn.cloud.validator.annotation.IdCard;
import com.learn.cloud.validator.constant.ValidatorConstants;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

import java.util.regex.Pattern;

/**
 * @description: 身份证校验器实现
 * @author: cong zhi
 * @createDate: 2022/2/6 16:40
 * @updateUser: cong zhi
 * @updateDate: 2022/2/6 16:40
 * @updateRemark: 修改内容
 * @version: v1.0
 */
public class IdCardValidator implements ConstraintValidator<IdCard, String> {

    private Boolean required;

    @Override
    public void initialize(IdCard constraintAnnotation) {
        this.required = constraintAnnotation.required();
    }

    @Override
    public boolean isValid(String idCardValue, ConstraintValidatorContext context) {
        if (StrUtil.isEmpty(idCardValue)) {
            if (required) {
                return false;
            }
            return true;
        }
        return Pattern.matches(ValidatorConstants.CARD_REGX, idCardValue);
    }
}
